args <- commandArgs(TRUE)
setwd(args[1])
library(survival)
geno<-read.table("temp_input",sep=" ",head=T)
#geno<-read.table("/data1/bsi/BORA_processing/devel/eqtl/parallelize_genotypingsurvival/input_withcorrecthead.tped",sep=" ",head=T)
rownames(geno)<-geno[,2]
clin<-read.delim("/data1/bsi/BORA_processing/devel/eqtl/parallelize_genotypingsurvival/clinical" ,sep="\t",quote="\"",dec=".",fill=TRUE,comment.char="",
header=TRUE,
col.names=c("SUBJECT","AGE","GENDER","OS","PFS","DFS","ALIVEOS","ALIVEPFS","ALIVEDFS","SITE"),as.is=c(TRUE,TRUE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,FALSE),colClasses=c("character","numeric","factor","numeric","numeric","numeric","integer","integer","integer","factor"))
clin$SUBJECT<-gsub("-",".",clin$SUBJECT)
samplesize<-20
num<-as.integer((length(geno[1,])-4)/samplesize)
num<-20
hazardrank<-matrix(nrow=nrow(geno), ncol=ncol(geno)-4)
rownames(hazardrank)<-geno[,2]
colgeno<-colnames(geno)
colnames(hazardrank)<-colgeno[5:length(colgeno)]
#predgmes(dt) <- c("SUBJECT","AGE","GENDER","OS","PFS","DFS","ALIVEOS","ALIVEPFS","ALIVEDFS","SITE","EXPR")ene<-c()
i<-1
while(i<nrow(geno)+1)
#while(i<3)
{
	geno1<-geno[i,5:ncol(geno)]
	d<-1
	while(d<num+1)
	{			
		s<-d;
		sub<-c()
		main<-c()
		if(d > 1)
		{
			main<-seq(1,d-1,1)
		}
		nu<-1
		while(s<length(geno1)+1)
		{
			sub[nu]<-s
			sequ<-c()		
			if(s+1 <= length(geno1))
			{	
				sequ<-seq(s+1,s+num-1,1)
				if(s+num-1 > length(geno1))
				{
					sequ<-seq(s+1,length(geno1),1)
				}
			}
			main<-c(main,sequ)
			nu<-nu+1	
			s<-s+num
		}
		#print(sub)
		genomain<-geno1[main]
		genosub<-geno1[sub]
		dt <- merge(clin,t(genomain),by.y="row.names",by.x="SUBJECT")
		colnames(dt) <- c("SUBJECT","AGE","GENDER","OS","PFS","DFS","ALIVEOS","ALIVEPFS","ALIVEDFS","SITE","EXPR")
		fit1 <- coxph(Surv(OS,ALIVEOS) ~ EXPR+AGE,data=dt)
		#pred<-geno1
		#pred <- predict(fit1, data.frame(cbind(genotype=geno1)), type="response")
		dt1 <-merge(clin,t(geno1),by.y="row.names",by.x="SUBJECT")
		colnames(dt1) <- c("SUBJECT","AGE","GENDER","OS","PFS","DFS","ALIVEOS","ALIVEPFS","ALIVEDFS","SITE","EXPR")
		pred <- predict(fit1, dt1,type="lp")
		#order_rank<-order(pred)
                #sorted_ranks<-seq(1,length(order_rank),1)
                #order_of_index<-order(order_rank)
                #anted_ranks<-sorted_ranks[order_of_index]
		wanted_ranks<-rank(pred)
		hazardrank[i,sub]<-wanted_ranks[sub]
		d<-d+1
	}
	#print(hazardrank[i,])
	print(i)
	i<-i+1
}
#colnames(hazardrank)<-colnames(geno)
write.table(hazardrank,"hazardrank.txt",quote=FALSE,sep="\t",col.names=TRUE,row.names=TRUE)
